from django.http import JsonResponse
from django.shortcuts import HttpResponse

from api import models


def demo(request):
    return JsonResponse({"status": True, "data": "OK"})

def fetch_task(request, did):
    # 1. did就是发来请求的设备ID(某个手机)
    #print("设备ID： ", did)
    # 2. 根据手机did查询，当前设备有没有人给他下发任务(去数据库查询)
    #    - 如果有，则获取第一个任务 并返回 {"status": True, "data": "OK"
    #    - 如果没有，返回 {"status": False, "data": "OK"

    # 2.1 获取设备ID
    device_object = models.Device.objects.filter(did=did).first()
    if not device_object:
        return JsonResponse({"status": False})
    #print(device_object.id)

    # 2.2 根据设备id查找任务, 待执行性的任务
    # models.Task.objects.filter(device_id=device_object.id, status=0).order_by("-id").first()  # desc 倒序
    task_row = models.Task.objects.filter(device_id=device_object.id, status=0).order_by("id").first() # asc
    if not task_row:
        return JsonResponse({"status": False})

    context = {
        "status": True,
        "address": task_row.address,
        "textList": task_row.text.split("\r\n"),
        "loopCount": task_row.loop_count,
        "taskId": task_row.id
    }

    # print(task_row.id, task_row.text, task_row.loop_count)

    return JsonResponse(context)


def running_task(request, task_id):
    # 根据任务id更新任务的状态，待执行-》执行中
    models.Task.objects.filter(id=task_id, status=0).update(status=1)
    return JsonResponse({"status": True})

def complete_task(request, task_id):
    # 根据任务id更新任务的状态，执行中-》已完成
    models.Task.objects.filter(id=task_id, status=1).update(status=2)
    return JsonResponse({"status": True})



















